package com.lineage.echo;

import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PacketHcZ implements Runnable {
	private static final Log _log = LogFactory.getLog(PacketHcZ.class);

	private final LinkedBlockingQueue<byte[]> _queue;

	private final PacketHandlerExecutor _handler;

	private final ClientExecutor _executor;

	public PacketHcZ(ClientExecutor executor) {
		_executor = executor;
		_queue = new LinkedBlockingQueue<byte[]>();
		_handler = new PackHanderZ(_executor);
	}

	public PacketHcZ(ClientExecutor executor, final int capacity) {
		_executor = executor;
		_queue = new LinkedBlockingQueue<byte[]>(capacity);
		_handler = new PackHanderZ(_executor);
	}

	public void requestWork(final byte data[]) {
		try {
			_queue.put(data);
		} catch (InterruptedException e) {
			_queue.clear();
		}
	}

	@Override
	public void run() {
		try {
			while (_executor.get_socket() != null) {
				final byte[] data = _queue.poll();
				if (data != null) {
					_handler.handlePacket(data);
				} else {
					Thread.sleep(10);
				}
			}
		} catch (final Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		} finally {
			_queue.clear();
		}
	}

}
